/*
 * @(#)FormGroupDAObject.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.dcivision.form.bean.FormGroup;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SqlAccountUtility;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.web.AbstractSearchForm;


/**
  FormGroupDAObject.java

  This class is the data access bean for table "FORM_GROUP".

  @author      Tony Chen
  @company     DCIVision Limited
  @creation date   17/02/2004
  @version     $Revision: 1.12 $
*/

public class FormGroupDAObject extends AbstractDAObject {

  public static final String REVISION = "$Revision: 1.12 $";

  public static final String TABLE_NAME = "FORM_GROUP";

  public FormGroupDAObject(SessionContainer sessionContainer, Connection dbConn) {
    super(sessionContainer, dbConn);
  }

  protected void initDBSetting() {
    this.baseTableName = TABLE_NAME;
    this.vecDBColumn.add("ID");
    this.vecDBColumn.add("GROUP_NAME");
    this.vecDBColumn.add("DESCRIPTION");
    this.vecDBColumn.add("RECORD_STATUS");
    this.vecDBColumn.add("UPDATE_COUNT");
    this.vecDBColumn.add("CREATOR_ID");
    this.vecDBColumn.add("CREATE_DATE");
    this.vecDBColumn.add("UPDATER_ID");
    this.vecDBColumn.add("UPDATE_DATE");
  }

  protected synchronized AbstractBaseObject getByID(Integer id) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.GROUP_NAME, A.DESCRIPTION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_GROUP A ");
        sqlStat.append("WHERE  A.ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, id);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          FormGroup tmpFormGroup = new FormGroup();
          tmpFormGroup.setID(getResultSetInteger(rs, "ID"));
          tmpFormGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpFormGroup.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpFormGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpFormGroup.getCreatorID()));
          tmpFormGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormGroup.getUpdaterID()));
          return(tmpFormGroup);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized List getList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.GROUP_NAME, A.DESCRIPTION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_GROUP A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        sqlStat.append(this.getIDFilterWhereClause("A"));

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 2, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 2, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormGroup tmpFormGroup = new FormGroup();
          tmpFormGroup.setID(getResultSetInteger(rs, "ID"));
          tmpFormGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpFormGroup.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpFormGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpFormGroup.getCreatorID()));
          tmpFormGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormGroup.getUpdaterID()));
          tmpFormGroup.setRecordCount(totalNumOfRecord);
          tmpFormGroup.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormGroup);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  protected synchronized List getList() throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.GROUP_NAME, A.DESCRIPTION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_GROUP A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        sqlStat.append(this.getIDFilterWhereClause("A"));

        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        while (rs.next()) {
          FormGroup tmpFormGroup = new FormGroup();
          tmpFormGroup.setID(getResultSetInteger(rs, "ID"));
          tmpFormGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpFormGroup.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpFormGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpFormGroup.getCreatorID()));
          tmpFormGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormGroup.getUpdaterID()));
          result.add(tmpFormGroup);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected void validateInsert(AbstractBaseObject obj) throws ApplicationException {
    FormGroup formGroup = (FormGroup)obj;
    StringBuffer sbSqlStat = new StringBuffer();
    PreparedStatement pstat = null;
    ResultSet rs = null;

    // Check duplicate user group name in the same group type.
    sbSqlStat.append("SELECT COUNT(*) ");
    sbSqlStat.append("FROM   FORM_GROUP ");
    sbSqlStat.append("WHERE  GROUP_NAME = ? AND RECORD_STATUS = ? ");
    sbSqlStat.append(this.getIDFilterWhereClause(null));

    try {
      pstat = this.dbConn.prepareStatement(sbSqlStat.toString());
      this.setPrepareStatement(pstat, 1, formGroup.getGroupName());
      this.setPrepareStatement(pstat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
      rs = pstat.executeQuery();
      if (rs.next() && rs.getInt(1)>0) {
        throw new ApplicationException(com.dcivision.workflow.WorkflowErrorConstant.DUPLICATE_GROUP_NAME);
      }
    } catch (java.sql.SQLException sqle) {
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
    } finally {
      try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
      try { pstat.close(); } catch (Exception ignore) {} finally { pstat = null; }
    }
  }

  protected void validateUpdate(AbstractBaseObject obj) throws ApplicationException {
    FormGroup formGroup = (FormGroup)obj;
    StringBuffer sbSqlStat = new StringBuffer();
    PreparedStatement pstat = null;
    ResultSet rs = null;

    // Check duplicate user group name in the same group type.
    sbSqlStat.append("SELECT COUNT(*) ");
    sbSqlStat.append("FROM   FORM_GROUP ");
    sbSqlStat.append("WHERE  GROUP_NAME = ? AND RECORD_STATUS = ? AND ID <> ? ");
    sbSqlStat.append(this.getIDFilterWhereClause(null));

    try {
      pstat = this.dbConn.prepareStatement(sbSqlStat.toString());
      this.setPrepareStatement(pstat, 1, formGroup.getGroupName());
      this.setPrepareStatement(pstat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
      this.setPrepareStatement(pstat, 3, formGroup.getID());
      rs = pstat.executeQuery();
      if (rs.next() && rs.getInt(1)>0) {
        throw new ApplicationException(com.dcivision.workflow.WorkflowErrorConstant.DUPLICATE_GROUP_NAME);
      }
    } catch (java.sql.SQLException sqle) {
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
    } finally {
      try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
      try { pstat.close(); } catch (Exception ignore) {} finally { pstat = null; }
    }
  }

  protected void validateDelete(AbstractBaseObject obj) throws ApplicationException {
  }

  protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    FormGroup tmpFormGroup = (FormGroup)((FormGroup)obj).clone();

    synchronized(dbConn) {
      try {
        Integer nextID = getNextPrimaryID();
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("INSERT ");
        sqlStat.append("INTO   FORM_GROUP(ID, GROUP_NAME, DESCRIPTION, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) ");
        sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, nextID);
        setPrepareStatement(preStat, 2, tmpFormGroup.getGroupName());
        setPrepareStatement(preStat, 3, tmpFormGroup.getDescription());
        setPrepareStatement(preStat, 4, GlobalConstant.RECORD_STATUS_ACTIVE);
        setPrepareStatement(preStat, 5, new Integer(0));
        setPrepareStatement(preStat, 6, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 7, currTime);
        setPrepareStatement(preStat, 8, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 9, currTime);
        preStat.executeUpdate();
        tmpFormGroup.setID(nextID);
        tmpFormGroup.setCreatorID(sessionContainer.getUserRecordID());
        tmpFormGroup.setCreateDate(currTime);
        tmpFormGroup.setUpdaterID(sessionContainer.getUserRecordID());
        tmpFormGroup.setUpdateDate(currTime);
        tmpFormGroup.setUpdateCount(new Integer(0));
        tmpFormGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpFormGroup.getCreatorID()));
        tmpFormGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormGroup.getUpdaterID()));
        return(tmpFormGroup);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    FormGroup tmpFormGroup = (FormGroup)((FormGroup)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE FORM_GROUP ");
        sqlStat.append("SET  GROUP_NAME=?, DESCRIPTION=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpFormGroup.getGroupName());
        setPrepareStatement(preStat, 2, tmpFormGroup.getDescription());
        setPrepareStatement(preStat, 3, new Integer(tmpFormGroup.getUpdateCount().intValue() + 1));
        setPrepareStatement(preStat, 4, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 5, currTime);
        setPrepareStatement(preStat, 6, tmpFormGroup.getID());
        setPrepareStatement(preStat, 7, tmpFormGroup.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          tmpFormGroup.setUpdaterID(sessionContainer.getUserRecordID());
          tmpFormGroup.setUpdateDate(currTime);
          tmpFormGroup.setUpdateCount(new Integer(tmpFormGroup.getUpdateCount().intValue() + 1));
          tmpFormGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpFormGroup.getCreatorID()));
          tmpFormGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormGroup.getUpdaterID()));
          return(tmpFormGroup);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject delete(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    FormGroup tmpFormGroup = (FormGroup)((FormGroup)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM   FORM_GROUP ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpFormGroup.getID());
        setPrepareStatement(preStat, 2, tmpFormGroup.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          return(tmpFormGroup);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized void auditTrail(String opMode, AbstractBaseObject obj) throws ApplicationException {
    Vector oldValues = new Vector();
    Vector newValues = new Vector();
    FormGroup tmpFormGroup = (FormGroup)this.oldValue;

    if (tmpFormGroup != null) {
      oldValues.add(toAuditTrailValue(tmpFormGroup.getID()));
      oldValues.add(toAuditTrailValue(tmpFormGroup.getGroupName()));
      oldValues.add(toAuditTrailValue(tmpFormGroup.getDescription()));
      oldValues.add(toAuditTrailValue(tmpFormGroup.getRecordStatus()));
      oldValues.add(toAuditTrailValue(tmpFormGroup.getUpdateCount()));
      oldValues.add(toAuditTrailValue(tmpFormGroup.getCreatorID()));
      oldValues.add(toAuditTrailValue(tmpFormGroup.getCreateDate()));
      oldValues.add(toAuditTrailValue(tmpFormGroup.getUpdaterID()));
      oldValues.add(toAuditTrailValue(tmpFormGroup.getUpdateDate()));
    }

    tmpFormGroup = (FormGroup)obj;
    if (tmpFormGroup != null) {
      newValues.add(toAuditTrailValue(tmpFormGroup.getID()));
      newValues.add(toAuditTrailValue(tmpFormGroup.getGroupName()));
      newValues.add(toAuditTrailValue(tmpFormGroup.getDescription()));
      newValues.add(toAuditTrailValue(tmpFormGroup.getRecordStatus()));
      newValues.add(toAuditTrailValue(tmpFormGroup.getUpdateCount()));
      newValues.add(toAuditTrailValue(tmpFormGroup.getCreatorID()));
      newValues.add(toAuditTrailValue(tmpFormGroup.getCreateDate()));
      newValues.add(toAuditTrailValue(tmpFormGroup.getUpdaterID()));
      newValues.add(toAuditTrailValue(tmpFormGroup.getUpdateDate()));
    }

    auditTrailBase(opMode, oldValues, newValues);
  }

  /***********************************************************************
   * DON'T Modify the codes above unless you know what you are doing!!!  *
   * Put your own functions beblow.                                      *
   * For FINDER methods, the function name should be in the notation:    *
   *   public Object getObjectBy<Criteria>()                             *
   *   - e.g. public Object getObjectByCode()                            *
   *   public List getListBy<Criteria>()                                 *
   *   - e.g. public List getListByUserID()                              *
   * For OPERATION methods, the function name should be in the notation: *
   *   public void <Operation>ObjectBy<Criteria>()                       *
   *   - e.g. public void deleteObjectByCode()                           *
   *   public void <Operation>ListBy<Criteria>()                         *
   *   - e.g. public void deleteListByUserID()                           *
   ***********************************************************************/

  public synchronized List getAccessibleList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.GROUP_NAME, A.DESCRIPTION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_GROUP A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        // Check Permission.
        List listID = this.sessionContainer.getPermissionManager().getAccessibleObjectIDList(GlobalConstant.OBJECT_TYPE_FORM);
        if (Utility.isEmpty(listID)) {
          sqlStat.append(" AND A.ID < 0 ");  // Hide all folders.
        } else {
          sqlStat.append(" AND (A.ID=" + ((Integer)listID.get(0)).toString());
          for (int i = 1 ; i < listID.size(); i++) {
            sqlStat.append(" OR A.ID=" + ((Integer)listID.get(i)).toString());
          }
          sqlStat.append(") ");
        }
        
        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());
        
        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 2, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 2, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormGroup tmpFormGroup = new FormGroup();
          tmpFormGroup.setID(getResultSetInteger(rs, "ID"));
          tmpFormGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpFormGroup.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpFormGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpFormGroup.getCreatorID()));
          tmpFormGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormGroup.getUpdaterID()));
          tmpFormGroup.setRecordCount(totalNumOfRecord);
          tmpFormGroup.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormGroup);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }
  
  public int getContainerFormCountByGroupID(String groupIDArr[]) throws ApplicationException {
	    int formCount = 0;

	    if (Utility.isEmpty(groupIDArr)) {
	      return formCount;
	    }

	    for (int i = 0; i < groupIDArr.length; i++) {
	      Integer integroupID = new Integer(groupIDArr[i]);
	      String formcondition = " FORM_GROUP_ID=" + integroupID.intValue() + " AND RECORD_STATUS='" + GlobalConstant.RECORD_STATUS_ACTIVE + "' ";
	      formCount = SqlAccountUtility.getIDCountFromSql(dbConn, "form_record", formcondition);
	      if (formCount != 0) {
	        return formCount;
	      }
	    }
	    return formCount;
	  }
  
  public synchronized List getAccessibleMonitoringReportList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());
    String type = ((com.dcivision.form.web.ListFormGroupRecordForm)searchForm).getListType();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.GROUP_NAME, A.DESCRIPTION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_GROUP A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        // Check Permission.
        List listID = this.sessionContainer.getPermissionManager().getAccessibleObjectIDList(GlobalConstant.OBJECT_TYPE_FORM, type);
        if (Utility.isEmpty(listID)) {
          sqlStat.append(" AND A.ID < 0 ");  // Hide all folders.
        } else {
          sqlStat.append(" AND (A.ID=" + ((Integer)listID.get(0)).toString());
          for (int i = 1 ; i < listID.size(); i++) {
            sqlStat.append(" OR A.ID=" + ((Integer)listID.get(i)).toString());
          }
          sqlStat.append(") ");
        }

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }
        
        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());
        
        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 2, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 2, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormGroup tmpFormGroup = new FormGroup();
          tmpFormGroup.setID(getResultSetInteger(rs, "ID"));
          tmpFormGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpFormGroup.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpFormGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpFormGroup.getCreatorID()));
          tmpFormGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormGroup.getUpdaterID()));
          tmpFormGroup.setRecordCount(totalNumOfRecord);
          tmpFormGroup.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormGroup);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }
}
